package com.sskj.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sskj.api.domain.Position;
import com.sskj.api.exception.LogicException;
import com.sskj.api.mapper.PositionMapper;
import com.sskj.api.service.ISysUserService;
import com.sskj.api.service.IPositionService;
import com.sskj.api.vo.req.PositionPageListReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
@Slf4j
public class PositionService extends ServiceImpl<PositionMapper, Position> implements IPositionService {

    @Autowired
    private ISysUserService adminUserService;

    @Override
    public void add(Position position) {
        LambdaQueryWrapper<Position> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Position::getDepartmentId, position.getDepartmentId())
                .eq(Position::getName, position.getName());
        if (count(lambdaQueryWrapper) > 0) {
            throw new LogicException("岗位已存在");
        }

        position.setCreateTime(LocalDateTime.now());
        save(position);
    }

    @Override
    public void deleteById(Long id) {
        Long count = adminUserService.countByPositionId(id);
        if (count > 0) {
            throw new LogicException("岗位关联用户，中止操作");
        }

        removeById(id);
    }

    @Override
    public void update(Position position) {
        LambdaQueryWrapper<Position> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.ne(Position::getId, position.getId())
                .eq(Position::getDepartmentId, position.getDepartmentId())
                .eq(Position::getName, position.getName());
        if (count(lambdaQueryWrapper) > 0) {
            throw new LogicException("岗位已存在");
        }

        position.setUpdateTime(LocalDateTime.now());
        updateById(position);
    }

    @Override
    public IPage<Position> pageList(PositionPageListReq req) {
        IPage<Position> pageConfig = new Page<>(req.getPageNum(), req.getPageSize());
        return baseMapper.pageList(pageConfig, req);
    }
}
